package pl.edu.agh.sius.gui.model;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.activation.DataHandler;

import pl.edu.agh.sius.invokers.SimpleServerInvoker;
import pl.edu.agh.sius.ldap.Ldap;
import pl.edu.agh.sius.schema.simplep2pserver.FileInfo;
import pl.edu.agh.sius.wsdl.simplep2pserver.SimpleP2PServerService;

public class FilesTableModel extends TableModel {
	private static final long serialVersionUID = -1653548400329661098L;
	
	private SimpleServerInvoker ssi;
	private Ldap ldap;

	public FilesTableModel(){
		super(new ArrayList<Object>());
		columns.add("File Name");
		columns.add("Size");
	}
	
	@SuppressWarnings("unchecked")
	public FilesTableModel(List<FileInfo> data){
		super((List<Object>)(List<?>)data);
		columns.add("File Name");
		columns.add("Size");
	}

	public Object getValueAt(int row, int col) {
		if(col == 0) {
			String tmp[] = ((FileInfo)dataList.get(row)).getFileName().split("\\\\");
			return tmp[tmp.length-1];
		}
		return ((FileInfo)dataList.get(row)).getFileSize() + " kB";
	}
	
	public List<FileInfo> getFiles(String selectedServer) {
		return ldap.getFilesList(selectedServer);
	}
	
	public void downloadFile(String selectedServer, FileInfo selectedFile) {
		if(selectedFile!=null) {
			ssi.setService(new SimpleP2PServerService(), selectedServer);
			
			DataHandler dh = ssi.download(selectedFile);
			
			FileOutputStream out = null;
			try {		
				String tmp[] = selectedFile.getFileName().split("\\\\");
				File file = new File("C:\\repository\\download\\" + tmp[tmp.length-1]);
			    if(!file.exists())
			    	file.createNewFile();

			    out = new FileOutputStream(file);
					
		      	dh.writeTo(out);
		       	out.flush();
		       	out.close();
		        	
			} catch (IOException e) {
				e.printStackTrace();
			}
			finally{
		       	try {
					out.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	}

	public SimpleServerInvoker getSsi() {
		return ssi;
	}

	public void setSsi(SimpleServerInvoker ssi) {
		this.ssi = ssi;
	}

	public Ldap getLdap() {
		return ldap;
	}

	public void setLdap(Ldap ldap) {
		this.ldap = ldap;
	}
	
	
}
